package com.whz.generic.crypt.sha;

import lombok.experimental.UtilityClass;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


/**
 * @author whz
 */
@UtilityClass
public class Sha256Utils {

  /**
   * 将加密后的字节数组转换成字符串
   */
  private static String byteArrayToHexString(byte[] b) {
    StringBuilder hs = new StringBuilder();
    String stmp;
    for (int n = 0; b != null && n < b.length; n++) {
      stmp = Integer.toHexString(b[n] & 0XFF);
      if (stmp.length() == 1) {
        hs.append('0');
      }
      hs.append(stmp);
    }
    return hs.toString().toLowerCase();
  }

  /**
   * sha256_HMAC加密
   *
   * @param message 消息
   * @param secret  秘钥
   * @return 加密后字符串
   */
  public static String sha256(String message, String secret) {
    try {
      Mac mac = Mac.getInstance("HmacSHA256");
      SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
      mac.init(secretKey);
      byte[] bytes = mac.doFinal(message.getBytes());
      return byteArrayToHexString(bytes);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}